<?php


namespace app\common\traits;





use app\common\helpers\Response;

trait ApiResponseTrait
{
    protected $httpCode = Response::HTTP_OK;
    protected $headers = [];

    final public function success($data)
    {
        return $this->respond($data);
    }

    final public function created($data)
    {
        return $this->setHttpCode(Response::HTTP_CREATED)->success($data);
    }

    final public function updated($data)
    {
        return $this->setHttpCode(Response::HTTP_ACCEPTED)->success($data);
    }

    final public function failed(string $err_msg = 'invalid argument', int $code = Response::HTTP_BAD_REQUEST)
    {
        return $this->setHttpCode($code)->respond([
            'code' => $code,
            'error' => $err_msg ?: Response::$statusTexts[$code],
        ]);
    }

    final public function setHttpCode(int $code = Response::HTTP_OK): object
    {
        $this->httpCode = $code;
        return $this;
    }

    final public function setHeader(array $headers = []): object
    {
        $this->headers = array_merge($this->headers, $headers);
        return $this;
    }

    private function respond($data)
    {
        $json_arr = [
            'data' => $data,
            'code' => $this->httpCode
        ];
        return json($json_arr)->code($this->httpCode)->header($this->headers);
    }
}
